// 如何判断树形数据结构最后一层，放入一个数组中
// 判断树形数据结构最后一层，并放入数组中
function getLastLevel(tree, result = []) {
  if (tree && Array.isArray(tree)) {
    for (const node of tree) {
      if (!node.children || !node.children.length) {
        result.push(node);
      } else {
        getLastLevel(node.children, result);
      }
    }
  }
  return result;
}

// 示例数据
const treeData = [
  { id: 1, name: "Node 1", children: [{ id: 11, name: "Node 1.1" }] },
  {
    id: 2,
    name: "Node 2",
    children: [
      { id: 21, name: "Node 2.1" },
      { id: 22, name: "Node 2.2", children: [{ id: 221, name: "Node 2.2.1" }] },
    ],
  },
  { id: 3, name: "Node 3", children: [] },
];

const lastLevelNodes = getLastLevel(treeData);
console.log(lastLevelNodes);
